/**
 * 模拟PHP sprintf 的函数
 * @returns string
 */
// 字符串格式化(%s )
function sprintf(str) {
  var args = arguments,
    flag = true,
    i = 1;
  str = str.replace(/%s/g, function () {
    var arg = args[i++];
    if (typeof arg === "undefined") {
      flag = false;
      return "";
    }
    return arg;
  });
  return flag ? str : "";
}

// 转换字符串，undefined,null等转化为""
function praseStrEmpty(str) {
  if (!str || str == "undefined" || str == "null") {
    return "";
  }
  return str;
}

/**
 * 判断是否是中文
 * @param {*} str
 * @returns
 */
function checkCh(str) {
  var pattern = new RegExp("[\\u4E00-\\u9FFF]", "g");
  return pattern.test(str);
}

/**
 * 计算字节长度utf8
 * @param {string} input value
 * @returns {number} output value
 */
function byteLength(str) {
  // returns the byte length of an utf8 string
  let s = str.length;
  for (var i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i);
    if (code > 0x7f && code <= 0x7ff) s++;
    else if (code > 0x7ff && code <= 0xffff) s += 2;
    if (code >= 0xdc00 && code <= 0xdfff) i--;
  }
  return s;
}

/**
 * @param {number} num 字符串长度
 * 获取随机唯一字符串
 * @returns {string}
 */
function createUniqueString(num) {
  const timestamp = +new Date() + "";
  const randomNum = parseInt((1 + Math.random()) * 65536) + "";
  return (+(randomNum + timestamp)).toString(num);
}

module.exports = {
  sprintf,
  praseStrEmpty,
  checkCh,
  byteLength,
  createUniqueString,
};
